package com.itheima.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    private ClazzService clazzService;

    /**
     * 分页查询学生
     * @param student
     * @return
     */
    @Override
    public PageResult pageStudent(StudentQueryParam student) {
        //1.构建分页参数
        Page<Student> pageParma = Page.of(student.getPage(), student.getPageSize());
        //2.构建分页条件并发起分页查询
        Page<Student> pageResult = this.lambdaQuery()
                .like(ObjectUtil.isNotEmpty(student.getName()) && student.getName() != null, Student::getName, student.getName())
                .eq(ObjectUtil.isNotEmpty(student.getDegree()), Student::getDegree, student.getDegree())
                .eq(ObjectUtil.isNotEmpty(student.getClazzId()), Student::getClazzId, student.getClazzId())
                .page(pageParma);
        //3.查出班级名封装到records中
        List<Student> records = pageResult.getRecords();
        for (Student record : records) {
            Clazz clazz = clazzService.getById(record.getClazzId());
            if (ObjectUtil.isNotEmpty(clazz)) {
                record.setClazzName(clazz.getName());
            }
        }
        //4.返回数据
        return new PageResult<>(pageResult.getTotal(), records);
    }

    /**
     * 扣分
     * @param id
     * @param score
     */
    @Override
    public void violation(Integer id, Integer score) {
        if (score >= 0) {
            this.lambdaUpdate().eq(Student::getId, id)
                    .setSql("violation_count=violation_count+" + 1)
                    .setSql("violation_score=violation_score+" + score)
                    .update();
        }
    }
}
